<?php
    session_start();
    require_once('../includes/DbConnector.php');
    
    if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
        $loggedIn = false;
        echo 'notloggedin';
    } else{
        $loggedIn = true;
    }
    
    if($loggedIn === true){
        if(isset($_POST['action']) && !empty($_POST['action'])) {
            $value = $_POST['value']; 
            $barid = $_POST['barid'];
            $userid = $_POST['userid'];
            $connector  = new DbConnector();
            //Check if user has rated bar before
            $sql = "select * from user_bar
                    where user_id = '$userid'
                    and bar_id = '$barid'";
            $result = $connector->query($sql);
            
            $a = mysql_fetch_assoc($result);
            
            if(json_encode($a) === 'false'){
                $sql2 = "insert into user_bar(user_id, bar_id, rating) 
                        VALUES('$userid', '$barid', '$value');";
                $result2 = $connector->query($sql2);
                if($result2){
                    echo "Success Insert Star";
                }
                
            } else{
                $sql3 = "update user_bar
                        set rating = '$value'
                        where user_id = '$userid'
                        and bar_id = '$barid'";
                $result3 = $connector->query($sql3);
                if($result3){
                    echo "Success Update Star";
                }
            }

            
        }
    }
    
?>